<template>
  <div class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input @change="handleChange" class="inp" type="text" :value="value">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>

<script>
export default {
  name: 'CountBox',

  props: {
    value: {
      type: Number,
      default: 1
    }
  },

  methods: {
    // 增加数量
    handleAdd () {
      this.$emit('input', this.value + 1)
    },

    // 减少数量
    handleSub () {
      if (this.value > 1) {
        this.$emit('input', this.value - 1)
      }
    },

    // 处理手动输入的场景
    handleChange (e) {
      const count = +e.target.value
      if (isNaN(count)) {
        e.target.value = this.value
        this.$toast('请输入数字')
        return
      }

      this.$emit('input', count)
    }
  }

}
</script>

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}

</style>
